#include <pthread.h>
#include<iostream>
#include <unistd.h>
using namespace std;

int tickets=1;
pthread_mutex_t mutex =PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond =PTHREAD_COND_INITIALIZER;

void* Run(void* args)
{
    string name = static_cast<const char*>(args);
    while(tickets>0)
    {
        pthread_mutex_lock(&mutex);
        cout<<"hhhh"<<endl;
        pthread_cond_wait(&cond,&mutex);
        if(tickets>0)
        {
            usleep(1000);
            cout<<"I am a thread "<<name<<" : "<<tickets--<<endl;
            pthread_mutex_unlock(&mutex);

        }
        else
        {
            // pthread_mutex_unlock(&mutex);
            break;
        }

    }
    cout<<name<<" haha"<<endl;

}
int main()
{
    pthread_t tid_1,tid_2,tid_3;
    pthread_create(&tid_1,nullptr,Run,(void*)"tid_1");
    pthread_create(&tid_2,nullptr,Run,(void*)"tid_2");
    pthread_create(&tid_3,nullptr,Run,(void*)"tid_3");

    // while(tickets>0)
    // {
    //     // pthread_cond_signal(&cond);
    //     pthread_cond_broadcast(&cond);
    //     usleep(100000);
    // }
    usleep(1000);
    pthread_cond_broadcast(&cond);//唤醒还在条件等待的线程


    pthread_join(tid_1,nullptr);
    pthread_join(tid_2,nullptr);
    pthread_join(tid_3,nullptr);

    return 0;
}